import json
import os

import xlrd
from django.http import JsonResponse
from django.shortcuts import render, redirect, HttpResponse
from openpyxl import load_workbook
from app03 import models

from django.views.decorators.csrf import csrf_exempt
from app03.utils.bootrsap import BootrsapModelForm
from app03.utils.pegination import Pegination


class OrderModelForm( BootrsapModelForm ):
    class Meta:
        model = models.QingJia
        fields = '__all__'


def order_list(request):
    # 对话框
    form = OrderModelForm()

    # 搜索框
    seach_list = request.GET.get( 'q', '' )
    data_t = {}
    if seach_list:
        data_t['user__contains'] = seach_list
    # 获取用户提交的信息
    daset = models.QingJia.objects.filter( **data_t )

    # 分页
    page_object = Pegination( request, daset, page_size=15 )
    context = {
        'daset': page_object.page_mun,
        'page_string': page_object.html(),
        'seach_list': seach_list,
        'form': form
    }

    return render( request, 'order_list.html', context )


# 新建请假
@csrf_exempt
def order_add(request):
    form = OrderModelForm( data=request.POST )
    if form.is_valid():
        form.save()
        data_dict = {'staut': True}
        return HttpResponse( json.dumps( data_dict ) )

    data_dict = {'staut': False, 'error': form.errors}
    # ensure_ascii=False
    return HttpResponse( json.dumps( data_dict ) )


# 销假窗口
def order_editGet(request):
    # 获取id
    uid = request.GET.get( 'uid' )
    # 根据id获取到对应行信息
    row_obj = models.QingJia.objects.filter( id=uid ).values( 'user', 'sex', 'age', 'deart', 'admins', 'times',
                                                              'retime', 'test' ).first()
    # 判断数据存不存在
    if not row_obj:
        return JsonResponse( {'staut': False, 'error': '数据不存在'} )
    result = {
        'staut': True,
        'data': row_obj
    }
    return JsonResponse( result )


# 编辑销假
@csrf_exempt
def order_edit(request):
    # 获取id
    uid = request.GET.get( 'uid' )
    # 根据id获取到对应行信息
    row_dict = models.QingJia.objects.filter( id=uid ).first()
    # 判断数据存不存在
    if not row_dict:
        return JsonResponse( {'staut': False, 'tpis': '数据不存在'} )
    form = OrderModelForm( data=request.POST, instance=row_dict )
    if form.is_valid():
        form.save()
        return JsonResponse( {'staut': True} )
    return HttpResponse( JsonResponse( {'staut': False, 'error': form.errors} ) )


# 删除请假条
def order_delete(request):
    uid = request.GET.get( 'uid' )
    exits = models.QingJia.objects.filter( id=uid ).exists()
    if not exits:
        return JsonResponse( {'stuat': False, 'error': '删除失败，数据不存在'} )
    models.QingJia.objects.filter( id=uid ).delete()
    return JsonResponse( {'stuat': True} )


# 上传文件
def order_upload(request):
    if request.method == 'GET':
        return render( request, 'order_upload.html' )
        # 2.对象传递给openpyxl,由openpyxl读取表格内容
    file_object = request.FILES.get('exc')
    wb = load_workbook( file_object )
    # 第0个sheet
    sheet =wb[wb.sheetnames[0]]
    prj=sheet.columns
    tom=tuple(prj)

    # 3.循环每一行的内容   iter_rows(min_row=2)从第二行开始
    for idx in range(0,len(tom)):
        for cell in tom[idx]:
            # user_s=cell[0].value
            # sex_s=cell[1].value
            print(cell.coordinate,cell.value)
            # exits = models.Deancte.objects.all().exists()
            # # 判断exits里面的数据是否存在数据库
            # if not exits:
            #     models.Deancte.objects.create( title=text )
    return redirect( '/order/list/' )
